<template>
  <div class="loginbackground">
    <div class="login_left">
      <h1>共享经济</h1>
      <p> 共享经济这个术语最早由美国德克萨斯州立大学社会学教授马科斯·费尔逊和伊利诺伊大学社会学教授琼·斯潘思于1978年发表的论文中提出。其主要特点是，包括一个由第三方创建的、以信息技术为基础的市场平台。这个第三方可以是商业机构、组织或者政府。个体借助这些平台，交换闲置物品，分享自己的知识、经验，或者向企业、某个创新项目筹集资金.</p>
    </div>

    <!-- 用户模块 -->
    <div class="user_card">
      <!-- 登录部分 -->
      <div class="login_right" v-show="showlogin">
        <div class="login-wrap">
          <img class="avatar" src="../assets/imgs/default.png">
          <el-form :model="loginFrom" status-icon :rules="loginFromRules" ref="loginruleForm" class="demo-ruleForm">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="loginFrom.email">
              </el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="loginFrom.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="loginbt_css" type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
          <div class="login_bm">
            <span>没有账号？前往这里☞<el-button class="logincheck" type="text" @click="checkoutregister">注册</el-button></span>
          </div>
        </div>
      </div>

      <!-- 注册部分 -->
      <div class="register_right" v-show="showregister" style="display:none">
        <div class="login-wrap">
          <img class="avatar" src="../assets/imgs/default.png">
          <el-form :model="registerForm" status-icon :rules="registerFormRules" ref="registerRuleForm" class="demo-ruleForm">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email">
              </el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="registerForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="loginbt_css" type="primary" @click="register">注册</el-button>
            </el-form-item>
            <div class="register_bm">
              <span>前往☞<el-button class="register" type="text" @click="checkoutlogin">登录</el-button></span>
            </div>
          </el-form>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const regemail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regemail.test(value)) {
        callback()
      }
      callback(new Error('邮箱输入错误!'))
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.checkPass !== '') {
          this.$refs.registerRuleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      showlogin: true,
      showregister: false,
      // 登录表单
      loginFrom: {
        email: '19990719@dxz.cn',
        password: '19990719'
      },

      // 注册表单
      registerForm: {
        email: '',
        password: '',
        checkPass: ''
      },
      // 登陆表单验证
      loginFromRules: {
        // 用户名验证规则
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 密码验证规则
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ]
      },
      // 注册表单验证
      registerFormRules: {
        // 用户名验证规则
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 密码验证规则
        password: [
          { validator: validatePass, trigger: 'blur' },
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        // 确认密码
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }, { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 获取登录状态
    async getuserstatus() {
      const res = await this.$http.get('/login/status')
      if (!res.data.isLogin) {
        return this.$message({
          showClose: true,
          message: '登录信息有误！',
          type: 'error'
        })
      }
      window.sessionStorage.setItem('userID', JSON.stringify(res.data.userId))
    },
    // 登录功能
    login() {
      this.$refs.loginruleForm.validate(async (valid) => {
        // console.log(valid)
        var that = this
        if (!valid) return
        await this.$http.post('/login', this.loginFrom).then((res) => {
          that.$message({
            showClose: true,
            message: '登录成功！',
            type: 'success'
          })
          // console.log(res)
          // 登陆成功后，将token信息存放到sessionStorage中
          window.sessionStorage.setItem('myuser', JSON.stringify(res.data))
          that.getuserstatus()
          // 通过编程式导航跳转到 home 组件
          that.$router.push('/myhome')
        }).catch((error) => {
          var messg = error.response.data.message + '!'
          // console.log(messg)
          that.$message({
            showClose: true,
            message: messg,
            type: 'error'
          })
        })
      })
    },

    // 注册切换
    checkoutregister() {
      this.showlogin = !this.showlogin
      this.showregister = !this.showregister
    },

    // 登录切换
    checkoutlogin() {
      this.showregister = !this.showregister
      this.showlogin = !this.showlogin
    },

    // 注册功能
    register() {
      this.$refs.registerRuleForm.validate(async (valid) => {
        if (!valid) return
        var registerforms = {
          avatar: this.InitializeAvatar,
          email: this.registerForm.email,
          nickName: '普通用户',
          password: this.registerForm.password,
          repassword: this.registerForm.checkPass,
          status: 1,
          role: 'normal'
        }
        const formdata = this.$qs.stringify(registerforms)
        // console.log(formdata)
        const res = await this.$http({
          method: 'post',
          url: '/users',
          data: formdata
        })
        if (res.status !== 200) {
          return this.$message({
            showClose: true,
            message: '登录失败！',
            type: 'error'
          })
        }
        this.$message({
          showClose: true,
          message: '登录成功！',
          type: 'success'
        })
        // 切换到登录模块
        this.checkoutlogin()
      })
    }
  }
}
</script>

<style scoped>
.loginbackground {
  position: relative;
  height: 100%;
  background: url(../assets/imgs/loginbg.jpg) no-repeat center;
}
.login_left {
  width: 500px;
  color: #FFF;
  font-size: 16px;
  line-height: 34px;
  position: absolute;
  left: 8%;
  top: 50%;
  transform: translate(0%,-75%);
}
.login-wrap {
    position: relative;
    top: 50%;
    left: 72%;
    transform: translate(-50%,28%);
    max-width: 450px;
    height: 600px;
    padding: 100px 40px 40px;
    border-radius: 4px;
    background-color: rgba(255, 255, 255, 0.5);
}

.login-wrap .avatar {
    position: absolute;
    top: -90px;
    left: 30%;
    overflow: hidden;
    width: 180px;
    height: 180px;
    border: 10px solid rgba(255, 255, 255, 0.5);
    border-radius: 50%;
    box-shadow: 0 1px 5px rgba(204, 204, 204, 0.7);
}

.loginbt_css {
  width: 100%;
  margin-top: 30px;
}

.login_bm{
  position: absolute;
  right: 10%;
  bottom: 14%;
}

.register_bm{
  position: absolute;
  right:10%;
  bottom: 5%;
}

.login_bm .logincheck,.register_bm .register{
  font-size:16px ;
  color: rgb(13, 10, 218);
  font-style:oblique
}
</style>
